<template>
	<div class="fillcontain">
		<div class="search_select">
			<div class="search_input">
				<span class="span-label">规则名称:</span>
				<el-input v-model="form.input" placeholder="请输入规则名称"> </el-input>
			</div>
			<div class="search_input">
				<span class="span-label">所属规则分类:</span>
				<el-select v-model="form.type" placeholder="请选择">
					<el-option v-for="item in optionsTwo" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</div>
			<div class="search_input">
				<span class="span-label">是否可用:</span>
				<el-select v-model="form.value" placeholder="请选择">
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</div>
			<div class="search_input">
				<span class="span-label">版本时间:</span>
				<el-select v-model="form.versionTime" placeholder="请选择">
					<el-option v-for="item in vTimeListData" :key="item.value" :label="item.label" :value="item.value"> </el-option>
				</el-select>
			</div>
			<div class="search_input">
				<el-button type="primary" @click="searchFun">查询</el-button>
				<el-button @click="resetFun">重置</el-button>
				<el-button v-auth="'data-qa-fe:rulesConfigurationManage:add'" type="primary" @click="add">新增</el-button>
			</div>
		</div>
		<div class="table_container">
			<el-table :data="tableData" border style="width: 100%">
				<el-table-column label="序号" type="index" width="60" align="center"> </el-table-column>
				<el-table-column label="规则名称" prop="ruleName"> </el-table-column>
				<el-table-column label="规则描述" prop="ruleDescription"> </el-table-column>
				<el-table-column label="所属规则分类" prop="ruleTypeId">
					<template #default="scope">
						{{ optionsTwo.length > 0 ? get_rule_type_name(scope.row.ruleTypeId) : '' }}
					</template>
				</el-table-column>
				<el-table-column label="规则参数类型" prop="ruleParameterType">
					<template #default="scope">
						<span v-if="scope.row.ruleParameterType == 1">SQL</span>
						<span v-if="scope.row.ruleParameterType == 2">代码块</span>
					</template>
				</el-table-column>
				<el-table-column label="规则参数" prop="ruleParameter" width="130" show-overflow-tooltip> </el-table-column>
				<el-table-column label="规则优先级" prop="rulePriority"> </el-table-column>
				<el-table-column label="版本时间" prop="versionId"> </el-table-column>
				<el-table-column label="是否有效" prop="invalidFlag">
					<template #default="scope">
						<span>{{ scope.row.invalidFlag == '0' ? '有效' : '无效' }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="160">
					<template #default="scope">
						<el-button v-auth="'data-qa-fe:rulesConfigurationManage:edit'" link size="small" type="primary" @click="handleEdit(scope.row)"
							>编辑</el-button
						>
						<el-button v-auth="'data-qa-fe:rulesConfigurationManage:delete'" link size="small" type="primary" @click="handleDelete(scope.row)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				:current-page="currentPage"
				:page-sizes="[10, 20, 50, 100, 200]"
				:page-size="limit"
				:total="count"
				layout="total, sizes, prev, pager, next, jumper"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			>
			</el-pagination>
		</div>
		<el-dialog v-model="dialog.visible" :title="dialog.title" width="30%" :before-close="dialogClose">
			<Form ref="modalFormRef" :form-state="formState" :form-data="formData"></Form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialog.visible = false">取 消</el-button>
					<el-button type="primary" :loading="dialog.loading" @click="dialogSave">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import {
	get_rules_config,
	get_rule_times,
	get_rule_type_dict,
	save_rule_template,
	update_rule_template,
	delete_rule_template
} from '@/api/data-qa-fe/index'
import { parseTime } from '@/utils/tool'
import Form from '@/components/Form/index.vue'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'

const modalFormRef = ref()
const dialog = ref({
	title: '新增规则',
	visible: false,
	loading: false
})
const formState = ref({
	id: '',
	ruleName: '',
	ruleDescription: '',
	ruleTypeId: '',
	rulePriority: '1',
	ruleParameter: '',
	versionId: parseTime(new Date(), '{y}{m}{d}'),
	invalidFlag: '0',
	note: '',
	ruleParameterType: 0
})
const formData = ref([
	{
		title: '规则名称',
		dataIndex: 'ruleName',
		type: 'input',
		rules: [{ required: true, message: '请输入规则名称', trigger: 'blur' }]
	},
	{
		title: '规则描述',
		dataIndex: 'ruleDescription',
		type: 'input',
		rules: [{ required: true, message: '请输入规则描述', trigger: 'blur' }]
	},
	{
		title: '规则分类',
		dataIndex: 'ruleTypeId',
		type: 'select',
		data: [],
		rules: [{ required: true, message: '请选择规则分类', trigger: 'change' }]
	},
	{
		title: '规则优先级',
		dataIndex: 'rulePriority',
		type: 'select',
		data: Array.from({ length: 9 }, (v, k) => {
			return {
				label: k + 1,
				value: k + 1
			}
		}),
		rules: [{ required: true, message: '请选择规则优先级', trigger: 'change' }]
	},
	{
		title: '规则参数类型',
		dataIndex: 'ruleParameterType',
		type: 'select',
		data: [
			{
				label: 'SQL',
				value: 1
			},
			{
				label: '代码块',
				value: 2
			}
		],
		rules: [{ required: true, message: '请选择规则参数类型', trigger: 'change' }]
	},
	{
		title: '规则参数',
		dataIndex: 'ruleParameter',
		type: 'textarea',
		rules: [{ required: true, message: '请输入规则参数', trigger: 'blur' }]
	},
	{
		title: '版本时间',
		dataIndex: 'versionId',
		type: 'day',
		disabled: true,
		format: 'YYYYMMDD'
	},
	{
		title: '是否有效',
		dataIndex: 'invalidFlag',
		type: 'switch',
		active: '0',
		inactive: '1'
	},
	{
		title: '备注',
		dataIndex: 'note',
		type: 'textarea'
	}
])
const optionsTwo = ref([])
const options = ref([
	{
		value: '',
		label: '全部'
	},
	{
		value: '0',
		label: '有效'
	},
	{
		value: '1',
		label: '无效'
	}
])
const form = ref({
	input: '',
	type: '',
	value: '',
	versionTime: ''
})
const vTimeListData = ref([])
const tableData = ref([])
const count = ref(0)
const total = ref(0)
const currentPage = ref(1)
const limit = ref(10)

onMounted(() => {
	init()
	getVTimes()
	get_rule_type_listFun()
})
const dialogClose = (done: Function) => {
	done()
}
const dialogReset = (item: any) => {
	const obj = {
		id: '',
		ruleName: '',
		ruleDescription: '',
		ruleTypeId: '',
		rulePriority: '',
		ruleParameter: '',
		versionId: parseTime(new Date(), '{y}{m}{d}'),
		invalidFlag: '0',
		note: ''
	}
	if (item) {
		formState.value = { ...obj, ...item }
		console.log('编辑', formState.value)
	} else {
		formState.value = { ...obj }
	}
}
const dialogSave = async () => {
	try {
		dialog.value.loading = true
		await modalFormRef.value.submit()
		let params: any = {
			...formState.value
		}
		params.rulePriority = params.ruleTypeId + '.' + params.rulePriority
		let res: any
		if (dialog.value.title === '新增规则') {
			res = await save_rule_template(params)
		} else {
			res = await update_rule_template(params)
		}
		console.log(res)
		if (res.code == 0) {
			ElMessage({
				message: res.msg,
				type: 'success'
			})
			dialog.value.loading = false
			dialog.value.visible = false
			init()
		} else {
			dialog.value.loading = false
			ElMessage({
				message: res.msg,
				type: 'error'
			})
		}
	} catch (e) {
		dialog.value.loading = false
		console.log(e)
	}
}
const add = () => {
	dialog.value.title = '新增规则'
	dialogReset({})
	dialog.value.visible = true
}
const handleEdit = (item: any) => {
	dialog.value.title = '编辑规则'
	let o: any = {}
	for (let key in formState.value) {
		o[key] = item[key]
	}
	const obj = {
		...o,
		rulePriority: (item.rulePriority + '').split('.')[1]
	}
	dialogReset(obj)
	dialog.value.visible = true
}
const handleDelete = (item: any) => {
	ElMessageBox.confirm('规则删除，会清除所有与本规则有关的核验关系，此操作确认删除后不可恢复，请慎重操作!', `确认删除【${item.ruleName}】规则吗？`, {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(() => {
			const params = {
				id: item.id
			}
			delete_rule_template(params).then((res: any) => {
				if (res.code == 0) {
					init()
					ElMessage({
						type: 'success',
						message: '删除成功'
					})
				} else {
					ElMessage({
						type: 'error',
						message: res.msg
					})
				}
			})
		})
		.catch(() => {
			console.log('取消')
		})
}
const init = () => {
	let param = {
		ruleName: form.value.input,
		ruleTypeName: form.value.type,
		invalidFlag: form.value.value,
		limit: limit.value,
		page: currentPage.value,
		versionId: form.value.versionTime
	}
	get_rules_config(param).then((res: any) => {
		if (res.code == 0) {
			tableData.value = res.data.list
			count.value = res.data.total
		}
	})
}
const getVTimes = () => {
	let param = {
		tablename: 'rule_template'
	}
	get_rule_times(param).then((res: any) => {
		console.log(res.data)
		vTimeListData.value.push({
			value: '',
			label: '全部'
		})
		vTimeListData.value = vTimeListData.value.concat(res.data)
	})
}
const get_rule_type_listFun = () => {
	let param = {}
	get_rule_type_dict(param).then((res: any) => {
		console.log(res.data)
		const item = formData.value.find(v => {
			return v.dataIndex === 'ruleTypeId'
		})
		item.data = res.data
		if (res.code == 0) {
			optionsTwo.value.push({
				value: '',
				label: '全部'
			})
			optionsTwo.value = optionsTwo.value.concat(res.data)
		}
	})
}
const get_rule_type_name = id => {
	let typeName = optionsTwo.value.filter(item => id == item.value)[0]?.label
	return typeName
}
const searchFun = () => {
	currentPage.value = 1
	init()
}
const resetFun = () => {
	form.value.input = ''
	form.value.type = ''
	form.value.value = ''
	form.value.versionTime = ''
	currentPage.value = 1
	limit.value = 10
	init()
}
const handleSizeChange = (val: any) => {
	limit.value = val
	init()
}
const handleCurrentChange = (val: any) => {
	console.log(`当前页: ${val}`)
	currentPage.value = val
	init()
}
</script>
<style lang="scss" scoped>
.fillcontain {
	background: #fff;
	padding: 20px;
	padding-top: 0;
}
.search_select {
	padding: 20px 20px 20px 0;
	display: flex;
	flex-wrap: wrap;
	.search_input {
		margin-bottom: 15px;
		margin-right: 15px;
	}
	.span-label {
		margin: 0 10px 0 20px;
	}
}
.el-input,
.el-input__inner {
	width: auto;
}
</style>
